/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package gui;

import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author hrushi
 */
public class ServerThread extends Thread {
    protected DatagramSocket socket = null;
    protected UnifiedForm form;
    public ServerThread(UnifiedForm f) {
        form = f;
        try {
            //System.out.println("Source: " + gui.UnifiedForm.SPORT);
            socket = new DatagramSocket(gui.UnifiedForm.SPORT);
        } catch (SocketException ex) {
            System.out.println("Inside serverthread constructor, socket exc");
            ex.printStackTrace();
        }
    }

    @Override
    public void run () {
        
        while (true) {
            if (gui.UnifiedForm.SERV_THR_RUN==true) {

                System.out.print("..");
                System.out.flush();

                try {
                    System.out.print("//");
                    System.out.flush();
                    byte[] buf = new byte[gui.UnifiedForm.MAXBUF];
                    DatagramPacket packet = new DatagramPacket(buf, buf.length);
                    socket.setSoTimeout(100);
                    socket.receive(packet);

                    //System.out.println("Here1" + this.getState());
                    System.out.flush();
                    ByteArrayInputStream byteStream = new ByteArrayInputStream(buf);
                    ObjectInputStream iStream = new ObjectInputStream(byteStream);
                    ChatMessage chat;

                    chat = (ChatMessage) iStream.readObject();
                    String temp = new String (chat.payload);
                    String temp1 = new String(chat.srcName);
                    
                    if (String.valueOf(chat.destName).trim().equals(form.getMyName().trim())) {
                        form.modifyMainTextArea(String.valueOf(chat.srcName) + ">> " + temp, "", 0, 0);
                    }
     
                    sleep(10);
                } catch (IOException exc) {
//                    System.out.println("Inside serverthread run");
     //               exc.printStackTrace();
                }catch (ClassNotFoundException exc) {
                    System.out.println("Inside serverthread class not found run");
     //               exc.printStackTrace();
                } catch (InterruptedException exc) {
                    System.out.println("Inside serverthread interrupted run");
    //                exc.printStackTrace();
                }
            }
        }
    }
}
